<template>
  <div class="app-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span class="main-title">错题组卷</span>
        </div>
      </template>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <!-- 试卷基本信息部分 -->
        <div class="section-header">
          <i class="el-icon-info"></i>
          <span>试卷信息</span>
        </div>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="试卷名称" prop="paper.paperName">
              <el-input v-model="form.paper.paperName" placeholder="请输入试卷名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="考试班级" prop="paper.classId">
              <el-select v-model="form.paper.classId" placeholder="请选择班级" filterable>
                <el-option
                  v-for="item in classList"
                  :key="item.classId"
                  :label="item.className"
                  :value="item.classId"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="考试时长" prop="paper.duration">
              <el-input-number v-model="form.paper.duration" :min="10" :max="1440" :step="10" 
                class="w-100" append-label="分钟" @change="handleDurationChange" />
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="考试时间" required>
              <el-row :gutter="10">
                <el-col :span="11">
                  <el-form-item prop="paper.startTime">
                    <el-date-picker 
                      v-model="form.paper.startTime" 
                      type="datetime" 
                      placeholder="开始时间"
                      value-format="YYYY-MM-DD HH:mm:ss"
                      format="YYYY-MM-DD HH:mm"
                      :disabled-date="disabledDate"
                      :disabled-time="disabledTime"
                      @change="handleStartTimeChange"
                      class="w-100" 
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="2" class="text-center">至</el-col>
                <el-col :span="11">
                  <el-form-item prop="paper.endTime">
                    <el-date-picker 
                      v-model="form.paper.endTime" 
                      type="datetime" 
                      placeholder="结束时间"
                      value-format="YYYY-MM-DD HH:mm:ss"
                      format="YYYY-MM-DD HH:mm"
                      :disabled-date="disabledEndDate"
                      class="w-100" 
                    />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 组卷信息部分 -->
        <div class="section-header">
          <i class="el-icon-setting"></i>
          <span>组卷信息</span>
        </div>
        <!-- 分数设置选项 -->
        <el-row>
          <el-col :span="24" class="score-setting-toggle">
            <el-switch
              v-model="useCustomScores"
              active-text="统一设置分数"
              inactive-text="采用原有分数"
              @change="handleScoreTypeChange"
            />
          </el-col>
        </el-row>

        <!-- 单选题设置 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="单选题个数">
              <el-input-number v-model="form.singleChoiceCount" :min="0" :max="50" class="w-100" />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="useCustomScores">
            <el-form-item label="单选题分值">
              <el-input-number v-model="form.singleChoiceScore" :min="0" :max="20" :precision="1" :step="0.5" class="w-100" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 多选题设置 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="多选题个数">
              <el-input-number v-model="form.multiChoiceCount" :min="0" :max="30" class="w-100" />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="useCustomScores">
            <el-form-item label="多选题分值">
              <el-input-number v-model="form.multiChoiceScore" :min="0" :max="20" :precision="1" :step="0.5" class="w-100" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 判断题设置 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="判断题个数">
              <el-input-number v-model="form.judgmentCount" :min="0" :max="30" class="w-100" />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="useCustomScores">
            <el-form-item label="判断题分值">
              <el-input-number v-model="form.judgmentScore" :min="0" :max="20" :precision="1" :step="0.5" class="w-100" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 填空题设置 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="填空题个数">
              <el-input-number v-model="form.fillBlankCount" :min="0" :max="20" class="w-100" />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="useCustomScores">
            <el-form-item label="填空题分值">
              <el-input-number v-model="form.fillBlankScore" :min="0" :max="20" :precision="1" :step="0.5" class="w-100" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 简答题设置 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="简答题个数">
              <el-input-number v-model="form.essayCount" :min="0" :max="10" class="w-100" />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="useCustomScores">
            <el-form-item label="简答题分值">
              <el-input-number v-model="form.essayScore" :min="0" :max="30" :precision="1" :step="1" class="w-100" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 按钮区域 -->
        <el-form-item class="button-group">
          <el-button type="primary" @click="handlePreview">预览</el-button>
          <el-button type="success" @click="selectQuestions">选择题目</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 选择题目对话框 -->
    <el-dialog 
      v-model="selectDialogVisible" 
      title="选择题目" 
      width="90%" 
      append-to-body
      destroy-on-close
    >
      <el-tabs v-model="activeTab" type="card">
        <el-tab-pane label="单选题" name="singleChoice" v-if="form.singleChoiceCount > 0">
          <question-selector
            :question-type="0"
            :max-select-count="form.singleChoiceCount"
            :selected-questions="selectedQuestions.singleChoice"
            @update:selected-questions="updateSelectedQuestions('singleChoice', $event)"
          />
        </el-tab-pane>
        <el-tab-pane label="多选题" name="multiChoice" v-if="form.multiChoiceCount > 0">
          <question-selector
            :question-type="1"
            :max-select-count="form.multiChoiceCount"
            :selected-questions="selectedQuestions.multiChoice"
            @update:selected-questions="updateSelectedQuestions('multiChoice', $event)"
          />
        </el-tab-pane>
        <el-tab-pane label="判断题" name="judgment" v-if="form.judgmentCount > 0">
          <question-selector
            :question-type="2"
            :max-select-count="form.judgmentCount"
            :selected-questions="selectedQuestions.judgment"
            @update:selected-questions="updateSelectedQuestions('judgment', $event)"
          />
        </el-tab-pane>
        <el-tab-pane label="填空题" name="fillBlank" v-if="form.fillBlankCount > 0">
          <question-selector
            :question-type="3"
            :max-select-count="form.fillBlankCount"
            :selected-questions="selectedQuestions.fillBlank"
            @update:selected-questions="updateSelectedQuestions('fillBlank', $event)"
          />
        </el-tab-pane>
        <el-tab-pane label="简答题" name="essay" v-if="form.essayCount > 0">
          <question-selector
            :question-type="4"
            :max-select-count="form.essayCount"
            :selected-questions="selectedQuestions.essay"
            @update:selected-questions="updateSelectedQuestions('essay', $event)"
          />
        </el-tab-pane>
      </el-tabs>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="selectDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="confirmSelectQuestions">确 定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 预览试卷对话框 -->
    <el-dialog 
      v-model="previewDialogVisible" 
      title="试卷预览" 
      width="80%" 
      append-to-body
      @opened="renderMathInPreview"
    >
      <div ref="previewContainer" class="paper-preview">
        <div class="paper-header">
          <h1>{{ form.paper.paperName || '未命名试卷' }}</h1>
          <div class="paper-info">
            <p>考试班级：{{ getClassName(form.paper.classId) || '未选择班级' }}</p>
            <p>考试时长：{{ form.paper.duration }}分钟</p>
            <p>总分：{{ calculateTotalScore() }}分</p>
          </div>
        </div>
        <div v-loading="previewLoading" class="paper-content">
          <!-- 单选题预览 -->
          <div v-if="selectedQuestions.singleChoice && selectedQuestions.singleChoice.length > 0" class="question-section">
            <h2>{{ getSectionTitle('singleChoice') }}（共{{ selectedQuestions.singleChoice.length }}题，共{{ calculateSectionScore('singleChoice') }}分）</h2>
            <div v-for="(question, index) in selectedQuestions.singleChoice" :key="'single-'+index" class="question-item">
              <div class="question-title">{{ index + 1 }}. <span class="score-tag">(本题{{ getQuestionScore(question) }}分)</span> <span v-html="processContent(question.questionContent)"></span></div>
              <div class="question-options">
                <div v-for="option in question.options" :key="option.optionLabel" class="question-option">
                  <span class="option-label">{{ option.optionLabel }}.</span>
                  <span class="option-content" v-html="processContent(option.optionContent)"></span>
                </div>
              </div>
            </div>
          </div>

          <!-- 多选题预览 -->
          <div v-if="selectedQuestions.multiChoice && selectedQuestions.multiChoice.length > 0" class="question-section">
            <h2>{{ getSectionTitle('multiChoice') }}（共{{ selectedQuestions.multiChoice.length }}题，共{{ calculateSectionScore('multiChoice') }}分）</h2>
            <div v-for="(question, index) in selectedQuestions.multiChoice" :key="'multi-'+index" class="question-item">
              <div class="question-title">{{ index + 1 }}. <span class="score-tag">(本题{{ getQuestionScore(question) }}分)</span> <span v-html="processContent(question.questionContent)"></span></div>
              <div class="question-options">
                <div v-for="option in question.options" :key="option.optionLabel" class="question-option">
                  <span class="option-label">{{ option.optionLabel }}.</span>
                  <span class="option-content" v-html="processContent(option.optionContent)"></span>
                </div>
              </div>
            </div>
          </div>

          <!-- 判断题预览 -->
          <div v-if="selectedQuestions.judgment && selectedQuestions.judgment.length > 0" class="question-section">
            <h2>{{ getSectionTitle('judgment') }}（共{{ selectedQuestions.judgment.length }}题，共{{ calculateSectionScore('judgment') }}分）</h2>
            <div v-for="(question, index) in selectedQuestions.judgment" :key="'judgment-'+index" class="question-item">
              <div class="question-title">{{ index + 1 }}. <span class="score-tag">(本题{{ getQuestionScore(question) }}分)</span> <span v-html="processContent(question.questionContent)"></span></div>
              <div class="question-options">
                <div class="question-option">
                  <span class="option-label">A.</span>
                  <span class="option-content">正确</span>
                </div>
                <div class="question-option">
                  <span class="option-label">B.</span>
                  <span class="option-content">错误</span>
                </div>
              </div>
            </div>
          </div>

          <!-- 填空题预览 -->
          <div v-if="selectedQuestions.fillBlank && selectedQuestions.fillBlank.length > 0" class="question-section">
            <h2>{{ getSectionTitle('fillBlank') }}（共{{ selectedQuestions.fillBlank.length }}题，共{{ calculateSectionScore('fillBlank') }}分）</h2>
            <div v-for="(question, index) in selectedQuestions.fillBlank" :key="'fill-'+index" class="question-item">
              <div class="question-title">{{ index + 1 }}. <span class="score-tag">(本题{{ getQuestionScore(question) }}分)</span> <span v-html="processContent(renderFillBlankQuestion(question.questionContent))"></span></div>
            </div>
          </div>

          <!-- 简答题预览 -->
          <div v-if="selectedQuestions.essay && selectedQuestions.essay.length > 0" class="question-section">
            <h2>{{ getSectionTitle('essay') }}（共{{ selectedQuestions.essay.length }}题，共{{ calculateSectionScore('essay') }}分）</h2>
            <div v-for="(question, index) in selectedQuestions.essay" :key="'essay-'+index" class="question-item">
              <div class="question-title">{{ index + 1 }}. <span class="score-tag">(本题{{ getQuestionScore(question) }}分)</span> <span v-html="processContent(question.questionContent)"></span></div>
            </div>
          </div>

          <div v-if="!hasSelectedQuestions" class="empty-data">
            请先选择题目
          </div>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="previewDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleSubmit">确认提交</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, nextTick, watch } from 'vue';
import { ElMessage, ElLoading } from 'element-plus';
import { useRouter, useRoute } from 'vue-router';
import { listGrade, getMyClasses } from "@/api/manage/grade";
import { createManualPaper } from "@/api/manage/paper";
import { getQuestion } from "@/api/manage/question";
import QuestionSelector from './components/WrongQuestionSelector.vue';
import useUserStore from '@/store/modules/user';

const router = useRouter();
const route = useRoute();
const formRef = ref(null);
const classList = ref([]);
const previewDialogVisible = ref(false);
const previewLoading = ref(false);
const previewContainer = ref(null);
const useCustomScores = ref(true); // 控制是否使用自定义分数
const now = new Date(); // 当前时间
const selectDialogVisible = ref(false);
const activeTab = ref('singleChoice');
const loading = ref(false);

// 难度文本
const difficultyTexts = ['简单', '较简单', '中等', '较难', '困难'];

// 已选择的题目
const selectedQuestions = reactive({
  singleChoice: [],
  multiChoice: [],
  judgment: [],
  fillBlank: [],
  essay: []
});

// 是否有已选择的题目
const hasSelectedQuestions = computed(() => {
  return selectedQuestions.singleChoice.length > 0 || 
         selectedQuestions.multiChoice.length > 0 || 
         selectedQuestions.judgment.length > 0 || 
         selectedQuestions.fillBlank.length > 0 || 
         selectedQuestions.essay.length > 0;
});

// 获取难度文本
const getDifficultyText = (value) => {
  return difficultyTexts[Math.round(value) - 1] || '未设置';
};

// 格式化本地时间
const formatLocalDateTime = (date) => {
  if (!date) return '';
  const d = new Date(date);
  
  const year = d.getFullYear();
  const month = String(d.getMonth() + 1).padStart(2, '0');
  const day = String(d.getDate()).padStart(2, '0');
  const hours = String(d.getHours()).padStart(2, '0');
  const minutes = String(d.getMinutes()).padStart(2, '0');
  const seconds = String(d.getSeconds()).padStart(2, '0');
  
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

// 禁用今天之前的日期
const disabledDate = (time) => {
  return time.getTime() < now.getTime() - 8.64e7; // 禁用昨天及之前的日期
};

// 禁用今天之前的时间
const disabledTime = (date) => {
  if (date && date.getDate() === now.getDate() && 
      date.getMonth() === now.getMonth() && 
      date.getFullYear() === now.getFullYear()) {
    return {
      hours: Array.from(Array(now.getHours()).keys()),
      minutes: date && date.getHours() === now.getHours() 
        ? Array.from(Array(now.getMinutes()).keys()) 
        : []
    };
  }
  return {
    hours: [],
    minutes: []
  };
};

// 禁用结束时间小于开始时间+考试时长的日期
const disabledEndDate = (time) => {
  if (!form.paper.startTime) return false;
  
  const startTime = new Date(form.paper.startTime);
  const minEndTime = new Date(startTime.getTime() + form.paper.duration * 60 * 1000);
  
  return time.getTime() < minEndTime.getTime();
};

// 处理考试时长变化
const handleDurationChange = () => {
  if (form.paper.startTime && form.paper.endTime) {
    const startTime = new Date(form.paper.startTime);
    const newEndTime = new Date(startTime.getTime() + form.paper.duration * 60 * 1000);
    
    // 如果当前结束时间小于新的最小结束时间，则更新结束时间
    const currentEndTime = new Date(form.paper.endTime);
    if (currentEndTime.getTime() < newEndTime.getTime()) {
      form.paper.endTime = formatLocalDateTime(newEndTime);
    }
  }
};

// 处理开始时间变化
const handleStartTimeChange = () => {
  if (form.paper.startTime) {
    const startTime = new Date(form.paper.startTime);
    const newEndTime = new Date(startTime.getTime() + form.paper.duration * 60 * 1000);
    form.paper.endTime = formatLocalDateTime(newEndTime);
  }
};

// 获取题型标题（自动编号）
const getSectionTitle = (type) => {
  const titles = {
    'singleChoice': '单选题',
    'multiChoice': '多选题',
    'judgment': '判断题',
    'fillBlank': '填空题',
    'essay': '简答题'
  };
  
  // 计算当前题型的顺序编号
  let index = 1;
  const types = ['singleChoice', 'multiChoice', 'judgment', 'fillBlank', 'essay'];
  
  for (const t of types) {
    if (t === type) {
      break;
    }
    
    if (selectedQuestions[t]?.length > 0) {
      index++;
    }
  }
  
  // 转换为中文数字
  const chineseNumbers = ['一', '二', '三', '四', '五'];
  return `${chineseNumbers[index-1]}、${titles[type]}`;
};

// 获取单个题目分数
const getQuestionScore = (question) => {
  if (!question) return 0;
  
  // 正确使用form.paper.useOriginalScore而不是useCustomScores
  if (form.paper.useOriginalScore) {
    // 使用题目原有分数
    return parseFloat(question.score || 0).toFixed(2);
  }
  
  // 使用统一设置的分数
  let score = 0;
  switch (question.questionType) {
    case 0: score = form.singleChoiceScore || 0; break;
    case 1: score = form.multiChoiceScore || 0; break;
    case 2: score = form.judgmentScore || 0; break;
    case 3: score = form.fillBlankScore || 0; break;
    case 4: score = form.essayScore || 0; break;
    default: score = 0;
  }
  
  return parseFloat(score).toFixed(2);
};

// 计算每种题型的总分
const calculateSectionScore = (type) => {
  const questions = selectedQuestions[type] || [];
  if (questions.length === 0) return 0;
  
  if (form.paper.useOriginalScore) {
    // 使用题目原有分数计算总分
    return questions.reduce((sum, q) => sum + (q.score || 0), 0);
  } else {
    // 使用统一设置的分数
    const scoreKey = `${type}Score`;
    return questions.length * (form[scoreKey] || 0);
  }
};

// 表单数据
const form = reactive({
  paper: {
    paperName: '',
    classId: '',
    duration: 120,
    startTime: '',
    endTime: '',
    status: 0, // 默认草稿状态
    useOriginalScore: false // 是否使用题目原分数
  },
  // 单选题设置
  singleChoiceCount: 5,
  singleChoiceScore: 2,
  // 多选题设置
  multiChoiceCount: 3,
  multiChoiceScore: 4,
  // 判断题设置
  judgmentCount: 5,
  judgmentScore: 1,
  // 填空题设置
  fillBlankCount: 3,
  fillBlankScore: 4,
  // 简答题设置
  essayCount: 1,
  essayScore: 10
});

// 校验规则
const rules = {
  'paper.paperName': [{ required: true, message: '请输入试卷名称', trigger: 'blur' }],
  'paper.classId': [{ required: true, message: '请选择班级', trigger: 'change' }],
  'paper.duration': [{ required: true, message: '请输入考试时长', trigger: 'blur' }],
  'paper.startTime': [{ required: true, message: '请选择开始时间', trigger: 'blur' }],
  'paper.endTime': [{ required: true, message: '请选择结束时间', trigger: 'blur' }]
};

// 处理分数设置方式变更
const handleScoreTypeChange = (val) => {
  console.log("分数设置切换:", val ? "统一设置分数" : "采用原有分数");
  
  // 更新分数设置属性
  form.paper.useOriginalScore = !val;
  
  // 确保useCustomScores和form.paper.useOriginalScore保持同步
  useCustomScores.value = val;
  
  // 如果切换为使用原始分数，确保每个题目的分数被正确应用
  if (!val) { // 采用原有分数
    console.log("切换到采用原有分数模式");
    // 此处不需要额外操作，因为在预览和提交时会使用题目原始分数
  } else { // 统一设置分数
    console.log("切换到统一设置分数模式");
    // 为每种题型设置默认分数或保持现有设置
    
    // 单选题
    if (selectedQuestions.singleChoice.length > 0) {
      // 如果已有统一分数，保持现有设置，否则使用第一个题目的分数或默认值
      if (!form.singleChoiceScore) {
        form.singleChoiceScore = selectedQuestions.singleChoice[0].score || 2.0;
      }
    } else if (!form.singleChoiceScore) {
      form.singleChoiceScore = 2.0; // 默认分数
    }
    
    // 多选题
    if (selectedQuestions.multiChoice.length > 0) {
      if (!form.multiChoiceScore) {
        form.multiChoiceScore = selectedQuestions.multiChoice[0].score || 4.0;
      }
    } else if (!form.multiChoiceScore) {
      form.multiChoiceScore = 4.0; // 默认分数
    }
    
    // 判断题
    if (selectedQuestions.judgment.length > 0) {
      if (!form.judgmentScore) {
        form.judgmentScore = selectedQuestions.judgment[0].score || 2.0;
      }
    } else if (!form.judgmentScore) {
      form.judgmentScore = 2.0; // 默认分数
    }
    
    // 填空题
    if (selectedQuestions.fillBlank.length > 0) {
      if (!form.fillBlankScore) {
        form.fillBlankScore = selectedQuestions.fillBlank[0].score || 3.0;
      }
    } else if (!form.fillBlankScore) {
      form.fillBlankScore = 3.0; // 默认分数
    }
    
    // 简答题
    if (selectedQuestions.essay.length > 0) {
      if (!form.essayScore) {
        form.essayScore = selectedQuestions.essay[0].score || 5.0;
      }
    } else if (!form.essayScore) {
      form.essayScore = 5.0; // 默认分数
    }
  }
  
  // 输出调试信息
  console.log("当前分数设置模式:", form.paper.useOriginalScore ? "采用原有分数" : "统一设置分数");
  console.log("useCustomScores:", useCustomScores.value);
};

// 计算总分
const calculateTotalScore = () => {
  let total = 0;
  // 计算每种题型的分数并累加
  total += calculateSectionScore('singleChoice');
  total += calculateSectionScore('multiChoice');
  total += calculateSectionScore('judgment');
  total += calculateSectionScore('fillBlank');
  total += calculateSectionScore('essay');
  return total;
};

// 处理内容，确保图片和数学公式正确显示
const processContent = (content) => {
  if (!content) return '';
  
  // 处理图片大小
  let processedContent = content;
  const tempDiv = document.createElement('div');
  tempDiv.innerHTML = processedContent;
  
  // 设置图片样式
  const images = tempDiv.querySelectorAll('img');
  images.forEach(img => {
    img.style.maxWidth = '100%';
    img.style.height = 'auto';
    img.style.objectFit = 'contain';
    // 添加加载错误处理
    img.onerror = function() {
      this.onerror = null;
      this.src = '/broken-image.jpg';
      this.alt = '图片加载失败';
    };
  });
  
  // 确保数学公式正确显示
  const mathElements = tempDiv.querySelectorAll('.math');
  mathElements.forEach(elem => {
    elem.style.display = 'inline-block';
    elem.style.maxWidth = '100%';
    elem.style.overflow = 'auto';
  });
  
  return tempDiv.innerHTML;
};

// 渲染填空题内容
const renderFillBlankQuestion = (content) => {
  if (!content) return '';
  return content.replace(/_{3,}/g, '<span class="blank-line">_________</span>');
};

// 打开选择题目对话框
const selectQuestions = () => {
  // 检查是否设置了题目数量
  const totalCount = form.singleChoiceCount + form.multiChoiceCount + form.judgmentCount + form.fillBlankCount + form.essayCount;
  if (totalCount === 0) {
    ElMessage.warning('请至少设置一种题型的题目数量');
    return;
  }
  
  // 设置默认激活的标签页
  if (form.singleChoiceCount > 0) {
    activeTab.value = 'singleChoice';
  } else if (form.multiChoiceCount > 0) {
    activeTab.value = 'multiChoice';
  } else if (form.judgmentCount > 0) {
    activeTab.value = 'judgment';
  } else if (form.fillBlankCount > 0) {
    activeTab.value = 'fillBlank';
  } else if (form.essayCount > 0) {
    activeTab.value = 'essay';
  }
  
  selectDialogVisible.value = true;
};

// 确认选择题目
const confirmSelectQuestions = () => {
  // 检查是否选择了足够数量的题目
  const checkTypeComplete = (type, count, typeName) => {
    if (selectedQuestions[type].length < count) {
      ElMessage.warning(`请为${typeName}选择${count}道题目，当前已选择${selectedQuestions[type].length}道`);
      return false;
    }
    return true;
  };
  
  let isComplete = true;
  if (form.singleChoiceCount > 0) {
    isComplete = isComplete && checkTypeComplete('singleChoice', form.singleChoiceCount, '单选题');
  }
  if (form.multiChoiceCount > 0 && isComplete) {
    isComplete = isComplete && checkTypeComplete('multiChoice', form.multiChoiceCount, '多选题');
  }
  if (form.judgmentCount > 0 && isComplete) {
    isComplete = isComplete && checkTypeComplete('judgment', form.judgmentCount, '判断题');
  }
  if (form.fillBlankCount > 0 && isComplete) {
    isComplete = isComplete && checkTypeComplete('fillBlank', form.fillBlankCount, '填空题');
  }
  if (form.essayCount > 0 && isComplete) {
    isComplete = isComplete && checkTypeComplete('essay', form.essayCount, '简答题');
  }
  
  if (isComplete) {
    selectDialogVisible.value = false;
    ElMessage.success('题目选择完成');
  }
};

// 更新已选择的题目
const updateSelectedQuestions = (type, questions) => {
  selectedQuestions[type] = questions;
};

// MathJax加载和渲染
const loadMathJax = () => {
  return new Promise((resolve) => {
    if (window.MathJax) {
      try {
        if (window.MathJax.typesetPromise) {
          window.MathJax.typesetPromise();
        } else if (window.MathJax.typeset) {
          window.MathJax.typeset();
        }
      } catch (e) {
        console.error('MathJax已加载但渲染失败:', e);
      }
      resolve(window.MathJax);
      return;
    }
    
    // 先创建配置
    window.MathJax = {
      tex: {
        inlineMath: [['$', '$'], ['\\(', '\\)']],
        displayMath: [['$$', '$$'], ['\\[', '\\]']]
      },
      svg: {
        fontCache: 'global'
      },
      output: {
        overflow: false
      },
      startup: {
        ready: () => {
          console.log('MathJax is ready');
          window.MathJax.startup.defaultReady();
          resolve(window.MathJax);
        }
      }
    };
    
    // 然后加载脚本
    const script = document.createElement('script');
    script.src = 'https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js';
    script.async = true;
    script.onload = () => {
      console.log('MathJax脚本已加载');
    };
    script.onerror = (e) => {
      console.error('MathJax加载失败:', e);
      // 尝试加载备用CDN
      const backupScript = document.createElement('script');
      backupScript.src = 'https://cdnjs.cloudflare.com/ajax/libs/mathjax/3.2.0/es5/tex-mml-chtml.js';
      backupScript.async = true;
      document.head.appendChild(backupScript);
    };
    document.head.appendChild(script);
  });
};

// 预览对话框打开后渲染数学公式
const renderMathInPreview = async () => {
  console.log('开始渲染公式');
  await nextTick();
  
  try {
    const mathJax = await loadMathJax();
    console.log('MathJax已加载', mathJax);
    // 确保内容已经渲染到DOM
    await nextTick();
    
    // 添加CSS来隐藏数学公式区域的滚动条
    const style = document.createElement('style');
    style.innerHTML = `
      .MJX-TEX { overflow: hidden !important; }
      .MathJax { overflow: hidden !important; }
      mjx-container { overflow: hidden !important; }
    `;
    document.head.appendChild(style);
    
    // 尝试多种方法渲染公式
    if (previewContainer.value) {
      if (mathJax.typesetPromise) {
        await mathJax.typesetPromise([previewContainer.value]);
        console.log('使用typesetPromise方法渲染完成');
      } else if (mathJax.typeset) {
        mathJax.typeset([previewContainer.value]);
        console.log('使用typeset方法渲染完成');
      } else {
        console.error('找不到MathJax的渲染方法');
      }
    } else {
      console.error('找不到预览容器');
    }
  } catch (error) {
    console.error('MathJax渲染错误:', error);
    // 作为备选方案，使用KaTeX尝试渲染
    try {
      if (!window.katex) {
        const link = document.createElement('link');
        link.rel = 'stylesheet';
        link.href = 'https://cdn.jsdelivr.net/npm/katex@0.16.4/dist/katex.min.css';
        document.head.appendChild(link);
        
        const script = document.createElement('script');
        script.src = 'https://cdn.jsdelivr.net/npm/katex@0.16.4/dist/katex.min.js';
        script.onload = () => {
          const autoRenderScript = document.createElement('script');
          autoRenderScript.src = 'https://cdn.jsdelivr.net/npm/katex@0.16.4/dist/contrib/auto-render.min.js';
          autoRenderScript.onload = () => {
            window.renderMathInElement(previewContainer.value, {
              delimiters: [
                {left: '$$', right: '$$', display: true},
                {left: '$', right: '$', display: false}
              ]
            });
          };
          document.head.appendChild(autoRenderScript);
        };
        document.head.appendChild(script);
      } else {
        window.renderMathInElement(previewContainer.value, {
          delimiters: [
            {left: '$$', right: '$$', display: true},
            {left: '$', right: '$', display: false}
          ]
        });
      }
    } catch (katexError) {
      console.error('KaTeX渲染备选方案也失败:', katexError);
    }
  }
};

// 获取班级列表
const getClassData = async () => {
  try {
    // 从store中获取当前用户角色
    const userStore = useUserStore();
    const roles = userStore.roles;
    
    if (roles.includes('teacher')) {
      // 教师角色：只获取自己任课的班级
      const res = await getMyClasses();
      classList.value = res.data || [];
    } else {
      // 管理员角色：获取所有班级
      const res = await listGrade();
      classList.value = res.rows.filter(item => item.status === 0); // 筛选启用状态的班级
    }
  } catch (err) {
    console.error('获取班级数据失败:', err);
    ElMessage.error('获取班级数据失败');
  }
};

// 预览试卷
const handlePreview = async () => {
  try {
  const valid = await formRef.value.validate()
  if (!hasSelectedQuestions.value) {
    ElMessage.warning('请先选择题目');
    return;
  }
  
  // 验证题目数量是否符合要求
  if (!validateQuestionCounts()) {
    return;
  }
  
  // 显示加载中状态
  previewLoading.value = true;
  previewDialogVisible.value = true;
  
  try {
    // 加载单选题选项
    for (const question of selectedQuestions.singleChoice) {
      if (!question.options || question.options.length === 0) {
        try {
          const res = await getQuestion(question.questionId);
          if (res.data && res.data.options) {
            question.options = res.data.options;
          }
        } catch (err) {
          console.error(`加载题目${question.questionId}选项失败:`, err);
        }
      }
    }
    
    // 加载多选题选项
    for (const question of selectedQuestions.multiChoice) {
      if (!question.options || question.options.length === 0) {
        try {
          const res = await getQuestion(question.questionId);
          if (res.data && res.data.options) {
            question.options = res.data.options;
          }
        } catch (err) {
          console.error(`加载题目${question.questionId}选项失败:`, err);
        }
      }
    }
  } catch (err) {
    console.error('加载题目选项失败:', err);
    ElMessage.warning('部分题目选项加载失败，预览可能不完整');
  } finally {
    previewLoading.value = false;
  }
}
catch (error) {
    // 表单验证失败时的处理
    ElMessage.warning('请填写必填项')
  }
};

// 验证题目数量是否符合要求
const validateQuestionCounts = () => {
  const countMismatches = [];
  
  if (selectedQuestions.singleChoice.length !== form.singleChoiceCount) {
    countMismatches.push(`单选题：已选${selectedQuestions.singleChoice.length}题，需要${form.singleChoiceCount}题`);
  }
  
  if (selectedQuestions.multiChoice.length !== form.multiChoiceCount) {
    countMismatches.push(`多选题：已选${selectedQuestions.multiChoice.length}题，需要${form.multiChoiceCount}题`);
  }
  
  if (selectedQuestions.judgment.length !== form.judgmentCount) {
    countMismatches.push(`判断题：已选${selectedQuestions.judgment.length}题，需要${form.judgmentCount}题`);
  }
  
  if (selectedQuestions.fillBlank.length !== form.fillBlankCount) {
    countMismatches.push(`填空题：已选${selectedQuestions.fillBlank.length}题，需要${form.fillBlankCount}题`);
  }
  
  if (selectedQuestions.essay.length !== form.essayCount) {
    countMismatches.push(`简答题：已选${selectedQuestions.essay.length}题，需要${form.essayCount}题`);
  }
  
  if (countMismatches.length > 0) {
    ElMessage.error('题目数量不符合要求：\n' + countMismatches.join('\n'));
    return false;
  }
  
  return true;
};

// 提交表单
const handleSubmit = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      if (!hasSelectedQuestions.value) {
        ElMessage.warning('请先选择题目');
        return;
      }
      
      // 验证题目数量是否符合要求
      if (!validateQuestionCounts()) {
        return;
      }
      
      try {
        console.log("提交时的分数设置模式:", form.paper.useOriginalScore ? "采用原有分数" : "统一设置分数");
        
        // 构建请求参数
        const params = {
          paper: {
            ...form.paper,
            // 确保传递所有必要的字段
            paperName: form.paper.paperName,
            classId: form.paper.classId,
            duration: form.paper.duration,
            startTime: form.paper.startTime,
            endTime: form.paper.endTime,
            status: form.paper.status,
            useOriginalScore: form.paper.useOriginalScore
          }
        };
        
        // 创建PaperQuestion对象列表
        const paperQuestions = [
          ...selectedQuestions.singleChoice.map((q, index) => ({
            questionId: q.questionId,
            questionScore: getQuestionScore(q),
            questionOrder: index + 1
          })),
          ...selectedQuestions.multiChoice.map((q, index) => ({
            questionId: q.questionId,
            questionScore: getQuestionScore(q),
            questionOrder: selectedQuestions.singleChoice.length + index + 1
          })),
          ...selectedQuestions.judgment.map((q, index) => ({
            questionId: q.questionId,
            questionScore: getQuestionScore(q),
            questionOrder: selectedQuestions.singleChoice.length + selectedQuestions.multiChoice.length + index + 1
          })),
          ...selectedQuestions.fillBlank.map((q, index) => ({
            questionId: q.questionId,
            questionScore: getQuestionScore(q),
            questionOrder: selectedQuestions.singleChoice.length + selectedQuestions.multiChoice.length + selectedQuestions.judgment.length + index + 1
          })),
          ...selectedQuestions.essay.map((q, index) => ({
            questionId: q.questionId,
            questionScore: getQuestionScore(q),
            questionOrder: selectedQuestions.singleChoice.length + selectedQuestions.multiChoice.length + selectedQuestions.judgment.length + selectedQuestions.fillBlank.length + index + 1
          }))
        ];
        
        // 输出调试信息
        console.log("即将提交的试卷：", JSON.stringify({
          ...params.paper,
          useOriginalScore: params.paper.useOriginalScore
        }));
        console.log("题目数量：", paperQuestions.length);
        
        // 新增模式
        params.selectedQuestions = paperQuestions; // 在新增模式下使用selectedQuestions参数
        const res = await createManualPaper(params);
        ElMessage.success('创建试卷成功');
        
        // 跳转到试卷列表页
        router.push('/paper/paper');
      } catch (err) {
        console.error('创建试卷失败:', err);
        ElMessage.error(err.message || '创建试卷失败');
      }
    } else {
      return false;
    }
  });
};

// 重置表单
const resetForm = () => {
  formRef.value.resetFields();
  useCustomScores.value = true;
  form.paper.useOriginalScore = false;
  
  // 清空已选择的题目
  Object.keys(selectedQuestions).forEach(key => {
    selectedQuestions[key] = [];
  });
  
  // 设置默认开始时间为当前时间
  const now = new Date();
  form.paper.startTime = formatLocalDateTime(now);
  
  // 设置默认结束时间
  const endTime = new Date(now.getTime() + form.paper.duration * 60 * 1000);
  form.paper.endTime = formatLocalDateTime(endTime);
};

// 初始化数据
onMounted(() => {
  getClassData();
  loadMathJax();
  
  // 设置默认开始时间为当前时间
  const now = new Date();
  form.paper.startTime = formatLocalDateTime(now);
  
  // 设置默认结束时间
  const endTime = new Date(now.getTime() + form.paper.duration * 60 * 1000);
  form.paper.endTime = formatLocalDateTime(endTime);
});

// 判断是否使用原始分数
const isUsingOriginalScores = () => {
  // 检查每种题型是否所有题目分数都相同
  const checkTypeScores = (questions) => {
    if (!questions || questions.length <= 1) return true;
    const firstScore = questions[0].score;
    return questions.every(q => q.score === firstScore);
  };
  
  // 检查所有题型
  const typesConsistent = 
    checkTypeScores(selectedQuestions.singleChoice) &&
    checkTypeScores(selectedQuestions.multiChoice) &&
    checkTypeScores(selectedQuestions.judgment) &&
    checkTypeScores(selectedQuestions.fillBlank) &&
    checkTypeScores(selectedQuestions.essay);
  
  return !typesConsistent;
};

// 根据题目类型获取分数
const getScoreByType = (type) => {
  const typeMap = {
    0: 'singleChoiceScore',
    1: 'multiChoiceScore',
    2: 'judgmentScore',
    3: 'fillBlankScore',
    4: 'essayScore'
  };
  
  return form[typeMap[type]] || 0;
};

// 监听题型数量变化，保持已选题目与数量一致
watch(() => form.singleChoiceCount, (newVal) => {
  if (selectedQuestions.singleChoice.length > newVal) {
    // 如果已选题目数量超过了设置的数量，则截取
    selectedQuestions.singleChoice = selectedQuestions.singleChoice.slice(0, newVal);
  }
});

watch(() => form.multiChoiceCount, (newVal) => {
  if (selectedQuestions.multiChoice.length > newVal) {
    selectedQuestions.multiChoice = selectedQuestions.multiChoice.slice(0, newVal);
  }
});

watch(() => form.judgmentCount, (newVal) => {
  if (selectedQuestions.judgment.length > newVal) {
    selectedQuestions.judgment = selectedQuestions.judgment.slice(0, newVal);
  }
});

watch(() => form.fillBlankCount, (newVal) => {
  if (selectedQuestions.fillBlank.length > newVal) {
    selectedQuestions.fillBlank = selectedQuestions.fillBlank.slice(0, newVal);
  }
});

watch(() => form.essayCount, (newVal) => {
  if (selectedQuestions.essay.length > newVal) {
    selectedQuestions.essay = selectedQuestions.essay.slice(0, newVal);
  }
});

// 获取班级名称
const getClassName = (classId) => {
  if (!classId) return undefined;
  const classItem = classList.value.find(item => item.classId === classId);
  return classItem ? classItem.className : undefined;
};
</script>
<style>
.ql-editor {
  min-height: 200px;
}
.ql-toolbar {
  background-color: #f8f8f8;
}
.ql-container {
  font-size: 14px;
}

/* 添加全局样式确保MathJax渲染正确 */
.MathJax {
  display: inline-block !important;
  margin: 0 0.2em;
  overflow: hidden !important;
}
/* 添加额外的样式确保KaTeX备选方案也能正确显示 */
.katex { 
  font-size: 1.1em !important;
  overflow: hidden !important;
}
/* 隐藏数学公式渲染区域的滚动条 */
mjx-container {
  overflow: hidden !important;
}

mjx-math {
  overflow: hidden !important;
}
.MJX-TEX {
  overflow: hidden !important;
}
/* 确保公式不会被裁剪 */
mjx-container[jax="CHTML"][display="true"] {
  max-width: 100%;
  overflow-x: auto;
  overflow-y: hidden;
}
</style>
<style scoped>
.app-container {
  padding: 20px;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.main-title {
  font-size: 18px;
  font-weight: bold;
  color: #303133;
}
.section-header {
  position: relative;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin: 20px 0;
  padding-left: 12px;
  border-left: 3px solid #409EFF;
  line-height: 1.2;
  background-color: #f5f7fa;
  padding: 10px 15px;
  border-radius: 4px;
}
.w-100 {
  width: 100%;
}
.text-center {
  text-align: center;
  line-height: 32px;
}
.score-setting-toggle {
  display: flex;
  justify-content: flex-end;
  margin: 5px 0;
}
.paper-preview {
  padding: 20px;
}
.paper-header {
  text-align: center;
  margin-bottom: 30px;
}
.paper-header h1 {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 10px;
}
.paper-info {
  display: flex;
  justify-content: center;
  gap: 20px;
}
.paper-content {
  padding: 0 10px;
}
.question-section {
  margin-bottom: 30px;
}
.question-section h2 {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 15px;
  border-bottom: 1px solid #ddd;
  padding-bottom: 8px;
}
.question-item {
  margin-bottom: 20px;
}
.question-title {
  font-size: 16px;
  margin-bottom: 10px;
  line-height: 1.5;
}
.question-options {
  padding-left: 20px;
}
.question-option {
  margin-bottom: 8px;
  line-height: 1.5;
  display: flex;
  align-items: flex-start;
}
.option-label {
  font-weight: bold;
  margin-right: 5px;
  min-width: 25px;
}
.option-content {
  flex: 1;
}
.blank-line {
  display: inline-block;
  min-width: 120px;
  border-bottom: 1px solid #000;
  margin: 0 5px;
  text-align: center;
}
.empty-data {
  text-align: center;
  color: #999;
  padding: 50px 0;
}
.button-group {
  display: flex;
  justify-content: center;
  margin-top: 30px;
}
.button-group .el-button {
  margin: 0 10px;
}
.preview-container {
  padding: 15px;
}
.preview-container img {
  max-width: 100% !important;
  height: auto !important;
  object-fit: contain !important;
}
.question-title img {
  max-width: 100% !important;
  height: auto !important;
  object-fit: contain !important;
}
.question-option img {
  max-width: 100% !important;
  height: auto !important;
  object-fit: contain !important;
}
/* 修改星级评分器样式 */
:deep(.el-rate) {
  margin-top: 5px;
  display: flex;
  height: 32px;
  line-height: 32px;
}
:deep(.el-rateicon) {
  font-size: 18px;
  margin-right: 3px;
}
:deep(.el-ratedecimal) {
  top: 0;
}
/* 优化选择下拉框样式 */
:deep(.el-select) {
  width: 100%;
}
:deep(.el-selecttags) {
  display: flex;
  flex-wrap: wrap;
  max-width: 100%;
}
:deep(.el-selecttags-text) {
  max-width: 120px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.score-tag {
  color: #409EFF;
  font-weight: bold;
  margin-right: 5px;
}
.edit-mode-tip {
  margin-left: 10px;
  margin-top: 5px;
  color: #E6A23C;
  font-size: 14px;
}
</style>